//
//  ShareViewController.m
//  51-Tour
//
//  Created by xiang ying on 14-3-19.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "ShareViewController.h"
#import <MessageUI/MessageUI.h>
#import "WXApi.h"
#import "SinaWeibo.h"
#import "SinaWeiboRequest.h"
#import "SVProgressHUD.h"
#import "TencentOpenAPI/QQApiInterface.h"
#import "ServiceManage.h"

#define SHARE_CONTENT       @"最近我使用了一款手机导游讲解APP--51导游，到达景区后，所有具游览价值的观赏点一目了然，在每个讲解点附近可以自动触发语音讲解，信号不好也可以手动点击讲解。太方便了！免费的哦！赶快下载："

typedef enum {
    Share_QQ,
    Share_wechat,
    Share_wechatSocial,
    Share_sina,
    Share_message,
}Share_type;

@interface ShareView : UIView<SinaWeiboDelegate, SinaWeiboRequestDelegate,WXApiDelegate,UITextViewDelegate>{
    UIView *contentView;
    UITextView *text;
    
    UILabel    *numLabel;
    
    Share_type shareType;
    SinaWeibo *weibo;
}

-(id)initWithShareType:(Share_type)type;
-(void)show;

@end

@implementation ShareView

-(id)initWithShareType:(Share_type)type{
    CGFloat height = [[UIScreen mainScreen] bounds].size.height;
    self = [super initWithFrame:CGRectMake(0, 0, 320, height)];
    if (self) {
        
        shareType = type;
        
        self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
        
        contentView = [[UIView alloc] initWithFrame:CGRectMake(0, height, 320, height-88)];
        contentView.backgroundColor = [UIColor whiteColor];
        [self addSubview:contentView];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.frame = CGRectMake(0, 0, 44, 44);
        [cancelBtn setImage:[UIImage imageNamed:@"ic-cancel_09"] forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(cancelShare:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:cancelBtn];
        
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(44, 0, 320-88, 44)];
        title.backgroundColor = [UIColor clearColor];
        title.textAlignment = NSTextAlignmentCenter;
        title.textColor = [UIColor darkGrayColor];
        switch (shareType) {
            case Share_QQ:
                title.text = [[DataCenter instance] getStringForKey:@"ShareQQ"];
                break;
            case Share_wechat:
                title.text = [[DataCenter instance] getStringForKey:@"ShareWeChat"];
                break;
            case Share_wechatSocial:
                title.text = [[DataCenter instance] getStringForKey:@"ShareWeChatSocial"];
                break;
            case Share_sina:{
                weibo = [[SinaWeibo alloc] initWithAppKey:kAppKey appSecret:kAppSecret appRedirectURI:kAppRedirectURI andDelegate:self];
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSDictionary *sinaweiboInfo = [defaults objectForKey:@"SinaWeiboAuthData"];
                if ([sinaweiboInfo objectForKey:@"AccessTokenKey"] && [sinaweiboInfo objectForKey:@"ExpirationDateKey"] && [sinaweiboInfo objectForKey:@"UserIDKey"])
                {
                    weibo.accessToken = [sinaweiboInfo objectForKey:@"AccessTokenKey"];
                    weibo.expirationDate = [sinaweiboInfo objectForKey:@"ExpirationDateKey"];
                    weibo.userID = [sinaweiboInfo objectForKey:@"UserIDKey"];
                }
                title.text = [[DataCenter instance] getStringForKey:@"ShareSina"];
            }
                break;
            default:
                break;
        }
        [contentView addSubview:title];
        
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sureBtn.frame = CGRectMake(320-44, 0, 44, 44);
        [sureBtn setImage:[UIImage imageNamed:@"ic-submit_09"] forState:UIControlStateNormal];
        [sureBtn addTarget:self action:@selector(sureShare:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:sureBtn];
        
        text = [[UITextView alloc] initWithFrame:CGRectMake(15, 50, 320-30, 88)];
        text.text = [DataCenter instance].shareText?[DataCenter instance].shareText:SHARE_CONTENT;
        text.delegate = self;
        text.layer.borderWidth = 1;
        text.layer.borderColor = BORDERCOLOR.CGColor;
        text.backgroundColor = [UIColor colorWithRed:229.0/255.0 green:229.0/255.0 blue:229.0/255.0 alpha:1.0];
        [contentView addSubview:text];
        
        numLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, text.frame.origin.y+text.frame.size.height, text.frame.size.width, 30)];
        numLabel.textAlignment = NSTextAlignmentRight;
        numLabel.font = [UIFont systemFontOfSize:14];
        numLabel.text = [NSString stringWithFormat:@"%d",121-SHARE_CONTENT.length];
        [contentView addSubview:numLabel];
    }
    return self;
}

-(void)show{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [text becomeFirstResponder];
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        contentView.center = CGPointMake(160, 88+contentView.frame.size.height/2);
    } completion:^(BOOL finished) {
        
    }];
}

-(void)cancelShare:(id)sender{
    [text resignFirstResponder];
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        contentView.center = CGPointMake(160, self.frame.size.height+contentView.frame.size.height/2);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)sureShare:(id)sender{
    //to do share
    switch (shareType) {
        case Share_QQ:{
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResp:) name:@"Resp" object:nil];
            QQApiTextObject *txtObj = [QQApiTextObject objectWithText:text.text];
            SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
            //将内容分享到qq
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
            
            NSString *msg = nil;
            if (sent == EQQAPISENDSUCESS) {
                return;
            }else if(sent == EQQAPIQQNOTINSTALLED){
                msg = @"未安装QQ";
            }else if(sent == EQQAPIQQNOTSUPPORTAPI){
                msg = @"QQ版本不支持";
            }else{
                msg = @"分享失败";
            }
            
            NSLog(@"%@",msg);
            if (sent!=EQQAPISENDSUCESS) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:msg delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
                [alert show];
            }
            [self cancelShare:nil];
        }
            break;
        case Share_wechat:
        case Share_wechatSocial:{
            //is wechat installed
            if ([WXApi isWXAppInstalled] == NO) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"未安装微信" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
                [alert show];
                [self cancelShare:nil];
                return;
            }else if ([WXApi isWXAppSupportApi] == NO){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:@"当前微信版本不支持" delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
                [alert show];
                [self cancelShare:nil];
                return;
            }
            //wechat
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResp:) name:@"Resp" object:nil];

            WXMediaMessage *message = [WXMediaMessage message];
            [message setThumbImage:[UIImage imageNamed:@"icon57-57"]];
            WXImageObject *ext = [WXImageObject object];
            ext.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"icon57-57"]);
            message.mediaObject = ext;
            message.description = text.text;
            
            SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
            req.bText = YES;
            req.text = text.text;
            req.message = message;
            req.scene = shareType-1;
            [WXApi sendReq:req];
        }
            break;
        case Share_sina:{
            if (weibo.isAuthValid) {
                //分享
                [SVProgressHUD showWithStatus:[[DataCenter instance] getStringForKey:@"loading"]];
                [weibo requestWithURL:@"statuses/update.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:text.text, @"status", nil]
                           httpMethod:@"POST"
                             delegate:self];
            }else{
                //授权
                [weibo logIn];
                [text resignFirstResponder];
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView{
    numLabel.text = [NSString stringWithFormat:@"%d",122-text.text.length];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (range.location>121) {
            return NO;
    }
    return YES;
}

#pragma mark share delegate

#pragma mark -
#pragma mark 用户绑定本地保存
- (void)removeAuthData
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
}

- (void)storeAuthData
{
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              weibo.accessToken, @"AccessTokenKey",
                              weibo.expirationDate, @"ExpirationDateKey",
                              weibo.userID, @"UserIDKey",
                              weibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    
    //    [self resetButtons];
    [self storeAuthData];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"授权成功" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alert show];
    [alert performSelector:@selector(dismissWithClickedButtonIndex:animated:) withObject:nil afterDelay:1.0];;
    [text becomeFirstResponder];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");
    [self removeAuthData];
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
    [text becomeFirstResponder];
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"授权失败"
                                                    message:nil
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles: nil];
    [alert show];
    [alert performSelector:@selector(dismissWithClickedButtonIndex:animated:) withObject:nil afterDelay:1.0];;
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    [self removeAuthData];
}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
//        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
//        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"分享失败"
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定", nil];
        [alertView show];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        
    }
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
//        [userInfo release];
//        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
//        [statuses release];
//        statuses = [[result objectForKey:@"statuses"] retain];
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"分享成功！"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        
        [self addShareLog:3];
        [self cancelShare:nil];
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" succeed!", [result objectForKey:@"text"]]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
    }
    [SVProgressHUD dismiss];
}

#pragma mark - sharelog

-(void)addShareLog:(int)tag{
    if ([DataCenter instance].user) {
        [ServiceManage shareRequestInfo:@{@"Mobile": [DataCenter instance].user.userPhone,@"ShareType":[NSString stringWithFormat:@"%d",tag]} completion:^(RespondDTO *respond) {
            NSLog(@"分享接口：%@",respond.msg);
        }];
    }
}

#pragma mark WXChat Delegate

- (void) onResp:(NSNotification*)response
{
    [self cancelShare:nil];
}

@end

#pragma mark -

@interface ShareViewController ()<UITableViewDataSource,UITableViewDelegate,MFMessageComposeViewControllerDelegate>{
    NSArray *_itemsArray,*_imagesArray;
}

@end

@implementation ShareViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initNavigationItme:[[DataCenter instance] getStringForKey:@"Share"]];
    
    _itemsArray = @[[[DataCenter instance] getStringForKey:@"ShareQQ"],
                    [[DataCenter instance] getStringForKey:@"ShareWeChat"],
                    [[DataCenter instance] getStringForKey:@"ShareWeChatSocial"],
                    [[DataCenter instance] getStringForKey:@"ShareSina"],
                    [[DataCenter instance] getStringForKey:@"ShareMessage"]];
    
    _imagesArray = @[@"qq_09",@"wechat_09",@"micro-message-circle_09",@"sina_09",@"sms_09"];
    
    UITableView *menu = [[UITableView alloc] initWithFrame:CGRectMake(10, 40, 320-20, 44*5)];
    menu.separatorStyle = UITableViewCellSeparatorStyleNone;
    [menu setBackgroundColor:[UIColor whiteColor]];
    menu.scrollEnabled = NO;
    menu.dataSource = self;
    menu.delegate = self;
    [self.contentView addSubview:menu];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)popself{
    [super popself];
    [[UIManagement shareInstance] showLeft];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _itemsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.backgroundColor = [UIColor clearColor];
        
        UIImageView *_line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"list-line_14"]];
        _line.frame = CGRectMake(0, 43, 320, 1);
        [cell addSubview:_line];
    }
    cell.textLabel.text = _itemsArray[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:_imagesArray[indexPath.row]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 4) {
        //message
        if ([MFMessageComposeViewController canSendText]) {
            
            MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
            picker.messageComposeDelegate = self;
            picker.body = SHARE_CONTENT;
            [self presentViewController:picker animated:YES completion:^{
                
            }];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"]
                                                            message:@"该设备不支持短信分享功能"
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:[[DataCenter instance] getStringForKey:@"Sure"], nil];
            [alert show];
        }

    }else{
        ShareView *share = [[ShareView alloc] initWithShareType:indexPath.row];
        [share show];
    }
}

#pragma mark -
#pragma mark MFMessageComposeViewControllerDelegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
	
	// Notifies users about errors associated with the interface
	switch (result) {
		case MessageComposeResultCancelled:
            //			if (DEBUG) NSLog(@"Result: canceled");
			break;
		case MessageComposeResultSent:
            //			if (DEBUG) NSLog(@"Result: Sent");
            NSLog(@"---%d",controller.recipients.count);
			break;
		case MessageComposeResultFailed:
            //			if (DEBUG) NSLog(@"Result: Failed");
			break;
		default:
			break;
	}
	[self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

@end
